package com.joker.service;

import com.joker.kehu.MyClient;
import com.joker.pojo.FileContext;
import com.joker.pojo.SendNetty;
import com.joker.util.FtpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class FileTimeService {
    HashMap<String, FileContext> fileContextHashMap=new HashMap<>();

    @Autowired
    PictureService pictureService;
    @Autowired
    MyClient myClient;
    @Scheduled(fixedDelay = 10000)
    public void file() throws Exception {

        String basePath = "D:\\doc\\java";
        File dir = new File(basePath);

        List<File> allFileList = new ArrayList<>();

        // 判断文件夹是否存在
        if (!dir.exists()) {
            System.out.println("目录不存在");
            return;
        }

        getAllFile(dir, allFileList);

        for (File file : allFileList) {
            FileContext fileContext = fileContextHashMap.get(file.getName());
            if (fileContext == null) {
                FileContext fileContext1 = new FileContext();
                fileContext1.setFileName(file.getName());
                fileContext1.setFilePath(file.getPath());
                fileContextHashMap.put(file.getName(),fileContext1);
                //文件上传至ftp
                pictureService.sendFtp(file);
                SendNetty sendNetty = new SendNetty();
                sendNetty.setFileName(file.getName());
                sendNetty.setFilePath(file.getPath());
                myClient.sendTcp(sendNetty,"localhost",6666);
            }
            System.out.println(file.getName());
        }
        System.out.println("该文件夹下共有" + allFileList.size() + "个文件");
    }

    public static void getAllFile(File fileInput, List<File> allFileList) {
        // 获取文件列表
        File[] fileList = fileInput.listFiles();
        assert fileList != null;
        for (File file : fileList) {
            if (file.isDirectory()) {
                // 递归处理文件夹
                // 如果不想统计子文件夹则可以将下一行注释掉
                getAllFile(file, allFileList);
            } else {
                // 如果是文件则将其加入到文件数组中
                allFileList.add(file);
            }
        }
    }
}
